<template>
  <div>
    <el-card>
      <el-tabs v-model="activeName" class="tabs" :before-leave="changeTab">
        <el-tab-pane label="问诊分派规则" name="first">
          <el-form
            :model="assignForm"
            :rules="assignFormRules"
            ref="assignFormRef"
            label-width="165px"
            label-position="left"
          >
            <div v-if="assignForm.id == '' || assignForm.editFlag == true">
              <el-form-item label="分派规则" prop="rule">
                <el-radio-group v-model="assignForm.rule">
                  <el-radio
                    :label="typeof assignForm.rule == 'string' ? '1' : 1"
                    >先入驻医院抢单，后自营内部医院派单</el-radio
                  >
                </el-radio-group>
              </el-form-item>
              <el-form-item label="抢单时间" prop="timeout">
                <el-input
                  placeholder=" 请输入医院抢单时间，超过时间将自动派至自营全职医院"
                  v-model.number="assignForm.timeout"
                >
                  <template slot="append">分钟</template>
                </el-input>
              </el-form-item>
              <el-form-item label="派单方式" prop="dispatch_mode">
                <el-radio-group v-model="assignForm.dispatch_mode">
                  <el-radio
                    :label="
                      typeof assignForm.dispatch_mode == 'string' ? '1' : 1
                    "
                    >按在线医生平均分配</el-radio
                  >
                  <el-radio
                    :label="
                      typeof assignForm.dispatch_mode == 'string' ? '2' : 2
                    "
                    >按在线医生星级分配</el-radio
                  >
                </el-radio-group>
              </el-form-item>
              <!-- <el-form
                :model="dispatchRuleForm"
                :rules="dispatchRuleFormRules"
                ref="dispatchRuleFormRef"
              >
                <span>派单规则</span>
                <el-table
                  :data="dispatchRuleForm.dispatchRuleTableData"
                  border
                  :row-class-name="tableRowClassName"
                  @select="handleSelect"
                  ref="multipleTable"
                >
                  <el-table-column label="医院名称【ID】">
                    <template slot-scope="scope">
                      {{ scope.row.hospital_name }}【{{
                        scope.row.hospital_id
                      }}】
                    </template>
                  </el-table-column>
                  <el-table-column label="所属服务商【ID】">
                    <template slot-scope="scope">
                      {{ scope.row.provider_name }}【{{
                        scope.row.provider_id
                      }}】
                    </template>
                  </el-table-column>
                  <el-table-column label="服务名称【ID】">
                    <template slot-scope="scope">
                      {{ scope.row.service_item_name }}【{{
                        scope.row.service_item_id
                      }}】
                    </template>
                  </el-table-column>
                  <el-table-column label="优先级">
                    <template slot-scope="scope">
                      <el-form-item
                        :prop="
                          'dispatchRuleTableData.' + scope.$index + '.sort'
                        "
                        :rules="dispatchRuleFormRules.sort"
                      >
                        <el-select
                          v-model="scope.row.sort"
                          placeholder="请选择"
                          clearable
                          @clear="clearSelect(scope.$index)"
                          @change="changePriority($event, scope.row)"
                        >
                          <el-option
                            v-for="(
                              item, index
                            ) in dispatchRuleForm.dispatchRuleTableData"
                            :key="index"
                            :label="index + 1"
                            :value="index + 1"
                          >
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column type="selection" width="55">
                  </el-table-column>
                </el-table>
              </el-form> -->
              <el-row>
                <el-button
                  class="theme-background-color"
                  @click="saveaAssignData"
                >
                  保存
                </el-button>
              </el-row>
            </div>
            <div v-else>
              <el-form-item label="分派规则">
                <span v-if="assignForm.rule == 1"
                  >先入驻和兼职医院抢单，后自营全职医院派单</span
                >
              </el-form-item>
              <el-form-item label="抢单时间">
                <span>{{ assignForm.timeout }}分钟</span>
              </el-form-item>
              <el-form-item label="派单方式">
                <span v-if="assignForm.dispatch_mode == 1"
                  >按在线医生平均分配</span
                >
                <span v-if="assignForm.dispatch_mode == 2"
                  >按在线医生星级分配</span
                >
              </el-form-item>
              <!-- <el-form
                :model="dispatchRuleForm"
                :rules="dispatchRuleFormRules"
                ref="dispatchRuleFormRef"
              >
                <span>派单规则</span>
                <el-table
                  :data="dispatchRuleForm.dispatchRuleTableData"
                  border
                  :row-class-name="tableRowClassName"
                  @select="handleSelect"
                  ref="multipleTable"
                >
                  <el-table-column label="医院名称【ID】">
                    <template slot-scope="scope">
                      {{ scope.row.hospital_name }}【{{
                        scope.row.hospital_id
                      }}】
                    </template>
                  </el-table-column>
                  <el-table-column label="所属服务商【ID】">
                    <template slot-scope="scope">
                      {{ scope.row.provider_name }}【{{
                        scope.row.provider_id
                      }}】
                    </template>
                  </el-table-column>
                  <el-table-column label="服务名称【ID】">
                    <template slot-scope="scope">
                      {{ scope.row.service_item_name }}【{{
                        scope.row.service_item_id
                      }}】
                    </template>
                  </el-table-column>
                  <el-table-column label="优先级">
                    <template slot-scope="scope">
                      {{ scope.row.sort }}
                    </template>
                  </el-table-column>
                </el-table>
              </el-form> -->
              <el-row>
                <el-button
                  class="theme-background-color"
                  @click="assignForm.editFlag = true"
                >
                  编辑
                </el-button>
              </el-row>
            </div>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="药品提成配置" name="second">
          <el-form
            :model="drugCommissionForm"
            :rules="drugCommissionFormRules"
            ref="drugCommissionFormRef"
            label-width="165px"
            label-position="left"
          >
            <div
              v-if="
                drugCommissionForm.id == '' ||
                drugCommissionForm.editFlag == true
              "
            >
              <el-form-item label="提成方式" prop="rule">
                <el-radio-group v-model="drugCommissionForm.rule">
                  <el-radio
                    :label="
                      typeof drugCommissionForm.rule == 'string' ? '1' : 1
                    "
                    >按订单总额比例提成</el-radio
                  >
                </el-radio-group>
              </el-form-item>
              <el-form-item label="提成比例" prop="rate">
                <el-input
                  placeholder=" 请输入按药品订单总额提成的比例"
                  v-model.number="drugCommissionForm.rate"
                >
                  <template slot="append">%</template>
                </el-input>
              </el-form-item>
              <el-row>
                <el-button
                  class="theme-background-color"
                  @click="saveCommissionData"
                >
                  保存
                </el-button>
              </el-row>
            </div>
            <div v-else>
              <el-form-item label="提成方式">
                <span v-if="drugCommissionForm.rule == 1"
                  >按订单总额比例提成</span
                >
              </el-form-item>
              <el-form-item label="提成比例">
                <span>{{ drugCommissionForm.rate }}%</span>
              </el-form-item>
              <el-row>
                <el-button
                  class="theme-background-color"
                  @click="drugCommissionForm.editFlag = true"
                >
                  编辑
                </el-button>
              </el-row>
            </div>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="推广提成配置" name="third">
          <el-form
            :model="popularizeForm"
            :rules="popularizeFormRules"
            ref="popularizeFormRef"
            label-width="165px"
            label-position="left"
          >
            <span class="greenTitle">提成规则</span>
            <div
              v-if="popularizeForm.id == '' || popularizeForm.editFlag == true"
            >
              <el-card>
                <el-form-item label="推广实体类型" prop="entity_type">
                  <el-select
                    v-model="popularizeForm.entity_type"
                    placeholder="请选择"
                    clearable
                  >
                    <el-option
                      label="商品"
                      :value="
                        typeof popularizeForm.entity_type == 'string' ? '1' : 1
                      "
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="提成方式" prop="rule">
                  <el-radio-group v-model="popularizeForm.rule">
                    <el-radio
                      :label="typeof popularizeForm.rule == 'string' ? '1' : 1"
                      >按商品固定金额提成</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
                <el-form
                  :model="popularizeRuleForm"
                  :rules="popularizeRuleFormRules"
                  ref="popularizeRuleFormRef"
                >
                  <span>提成规则</span>
                  <el-button
                    type="text"
                    icon="el-icon-circle-plus-outline"
                    @click="addCommodity"
                    style="float: right"
                    >添加商品</el-button
                  >
                  <el-table
                    :data="popularizeRuleForm.ruleTableData"
                    border
                    :row-class-name="tableRowClassName"
                  >
                    <el-table-column label="商品名称【ID】">
                      <template slot-scope="scope">
                        {{ scope.row.goods_name }}【{{ scope.row.goods_id }}】
                      </template>
                    </el-table-column>
                    <el-table-column label="商品类别">
                      <template slot-scope="scope">
                        {{ scope.row.goods_class.name }}【{{
                          scope.row.goods_class.id
                        }}】
                      </template>
                    </el-table-column>
                    <el-table-column label="提成金额">
                      <template slot-scope="scope">
                        <el-form-item
                          :prop="'ruleTableData.' + scope.$index + '.fee'"
                          :rules="[
                            {
                              required: true,
                              message: '请输入',
                              trigger: 'change'
                            }
                          ]"
                        >
                          <el-input
                            v-model="scope.row.fee"
                            maxlength="8"
                            placeholder="请输入"
                          ></el-input>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="80px">
                      <template slot-scope="scope">
                        <el-link
                          type="primary"
                          :underline="false"
                          @click="deleteCommodity(scope.$index)"
                          >删除</el-link
                        >
                      </template>
                    </el-table-column>
                  </el-table>
                </el-form>
              </el-card>
            </div>
            <div v-else>
              <el-card>
                <el-form-item label="推广实体类型">
                  <span v-if="popularizeForm.entity_type == 1">商品</span>
                </el-form-item>
                <el-form-item label="提成方式">
                  <span v-if="popularizeForm.rule == 1"
                    >按商品固定金额提成</span
                  >
                </el-form-item>
                <el-form
                  :model="popularizeRuleForm"
                  :rules="popularizeRuleFormRules"
                  ref="popularizeRuleFormRef"
                >
                  <span>提成规则</span>
                  <el-table
                    :data="popularizeRuleForm.ruleTableData"
                    border
                    :row-class-name="tableRowClassName"
                  >
                    <el-table-column label="商品名称【ID】">
                      <template slot-scope="scope">
                        {{ scope.row.goods_name }}【{{ scope.row.goods_id }}】
                      </template>
                    </el-table-column>
                    <el-table-column label="商品类别">
                      <template slot-scope="scope">
                        {{ scope.row.goods_class.name }}【{{
                          scope.row.goods_class.id
                        }}】
                      </template>
                    </el-table-column>
                    <el-table-column label="提成金额">
                      <template slot-scope="scope">
                        {{ scope.row.fee }}
                      </template>
                    </el-table-column>
                  </el-table>
                </el-form>
              </el-card>
            </div>
          </el-form>
          <el-row style="margin-top: 20px">
            <el-button
              class="theme-background-color"
              @click="saveSpreadData"
              v-if="popularizeForm.id == '' || popularizeForm.editFlag == true"
            >
              保存
            </el-button>
            <el-button
              class="theme-background-color"
              @click="popularizeForm.editFlag = true"
              v-else
            >
              编辑
            </el-button>
          </el-row>
          <ChooseMultiCommodityDialog
            :chooseMultiCommodityDialogVisible.sync="
              chooseMultiCommodityDialogVisible
            "
            :commodityOptionalData="commodityOptionalData"
            @showCommodityData="getCommodityData"
          ></ChooseMultiCommodityDialog>
        </el-tab-pane>
        <el-tab-pane label="配送售后配置" name="fourth">
          <el-form
            :model="distributionForm"
            :rules="distributionFormRules"
            ref="distributionFormRef"
            label-width="165px"
            label-position="left"
          >
            <span class="greenTitle">配送规则</span>
            <div
              v-if="
                distributionForm.id == '' || distributionForm.editFlag == true
              "
            >
              <el-card>
                <el-form-item label="配送方式" prop="rule">
                  <el-select
                    v-model="distributionForm.rule"
                    placeholder="请选择"
                    clearable
                  >
                    <el-option
                      label="配送到家"
                      :value="
                        typeof distributionForm.rule == 'string' ? '1' : 1
                      "
                    ></el-option>
                    <el-option
                      label="普通快递"
                      :value="
                        typeof distributionForm.rule == 'string' ? '2' : 2
                      "
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="配送时效" prop="time_long">
                  <el-input
                    placeholder=" 请输入订单配送到家的时效，将用于客户端显示"
                    v-model.number="distributionForm.time_long"
                  >
                    <template slot="append">小时</template>
                  </el-input>
                </el-form-item>
                <el-form
                  :model="distributionRuleForm"
                  :rules="distributionRuleFormRules"
                  ref="distributionRuleFormRef"
                >
                  <span>配送规则</span>
                  <el-button
                    type="text"
                    icon="el-icon-circle-plus-outline"
                    @click="addHospital"
                    style="float: right"
                    >添加医院</el-button
                  >
                  <el-table
                    :data="distributionRuleForm.distributionRulesTable"
                    border
                    :row-class-name="tableRowClassName"
                  >
                    <el-table-column label="医院名称【ID】">
                      <template slot-scope="scope">
                        {{ scope.row.hospital_name }}【{{
                          scope.row.hospital_id
                        }}】
                      </template>
                    </el-table-column>
                    <el-table-column label="所属服务商【ID】">
                      <template slot-scope="scope">
                        {{ scope.row.provider_name }}【{{
                          scope.row.provider_id
                        }}】
                      </template>
                    </el-table-column>
                    <el-table-column label="配送范围（公里）">
                      <template slot-scope="scope">
                        <el-form-item
                          :prop="
                            'distributionRulesTable.' + scope.$index + '.range'
                          "
                          :rules="distributionRuleFormRules.range"
                        >
                          <el-input
                            v-model="scope.row.range"
                            maxlength="8"
                            placeholder="请输入"
                          ></el-input>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column label="配送费">
                      <template slot-scope="scope">
                        <el-form-item
                          :prop="
                            'distributionRulesTable.' + scope.$index + '.fee'
                          "
                          :rules="distributionRuleFormRules.fee"
                        >
                          <el-input
                            v-model="scope.row.fee"
                            maxlength="8"
                            placeholder="请输入"
                          ></el-input>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column label="免运费条件" width="90px">
                      无
                    </el-table-column>
                    <el-table-column label="操作" width="80px">
                      <template slot-scope="scope">
                        <el-link
                          type="primary"
                          :underline="false"
                          @click="deleteHospital(scope.$index)"
                          >删除</el-link
                        >
                      </template>
                    </el-table-column>
                  </el-table>
                </el-form>
              </el-card>
            </div>
            <div v-else>
              <el-card>
                <el-form-item label="配送方式">
                  <span v-if="distributionForm.rule == 1">配送到家</span>
                  <span v-if="distributionForm.rule == 2">普通快递</span>
                </el-form-item>
                <el-form-item label="配送时效">
                  <span>{{ distributionForm.time_long }}小时</span>
                </el-form-item>
                <el-form
                  :model="distributionRuleForm"
                  :rules="distributionRuleFormRules"
                  ref="distributionRuleFormRef"
                >
                  <span>配送规则</span>
                  <el-table
                    :data="distributionRuleForm.distributionRulesTable"
                    border
                    :row-class-name="tableRowClassName"
                  >
                    <el-table-column label="医院名称【ID】">
                      <template slot-scope="scope">
                        {{ scope.row.hospital_name }}【{{
                          scope.row.hospital_id
                        }}】
                      </template>
                    </el-table-column>
                    <el-table-column label="所属服务商【ID】">
                      <template slot-scope="scope">
                        {{ scope.row.provider_name }}【{{
                          scope.row.provider_id
                        }}】
                      </template>
                    </el-table-column>
                    <el-table-column label="配送范围（公里）">
                      <template slot-scope="scope">
                        {{ scope.row.range }}
                      </template>
                    </el-table-column>
                    <el-table-column label="配送费">
                      <template slot-scope="scope">
                        {{ scope.row.fee }}
                      </template>
                    </el-table-column>
                    <el-table-column label="免运费条件" width="90px">
                      无
                    </el-table-column>
                  </el-table>
                </el-form>
              </el-card>
            </div>
          </el-form>
          <el-form
            :model="afterSaleForm"
            :rules="afterSaleFormRules"
            ref="afterSaleFormRef"
            label-width="165px"
            label-position="left"
          >
            <span class="greenTitle">售后规则</span>
            <div
              v-if="afterSaleForm.id == '' || afterSaleForm.editFlag == true"
            >
              <el-card>
                <el-form-item
                  label="是否设置自动确认收货"
                  prop="is_auto_confirm"
                >
                  <el-radio-group v-model="afterSaleForm.is_auto_confirm">
                    <el-radio
                      :label="
                        typeof afterSaleForm.is_auto_confirm == 'string'
                          ? '1'
                          : 1
                      "
                      >是</el-radio
                    ><el-radio
                      :label="
                        typeof afterSaleForm.is_auto_confirm == 'string'
                          ? '0'
                          : 0
                      "
                      >否</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
                <el-form-item
                  label="自动确认收货时间"
                  prop="timeout_auto_confirm"
                  v-show="afterSaleForm.is_auto_confirm == 1"
                  :rules="
                    afterSaleForm.is_auto_confirm == 1
                      ? [
                          {
                            required: true,
                            message: '请输入',
                            trigger: 'blur'
                          },
                          { type: 'number', message: '必须为数字值' }
                        ]
                      : []
                  "
                >
                  <el-input
                    placeholder=" 请输入订单发货后，系统自动确认收货的时间"
                    v-model.number="afterSaleForm.timeout_auto_confirm"
                  >
                    <template slot="append">天</template>
                  </el-input>
                </el-form-item>
                <el-form-item label="退换货" prop="reject_mode">
                  <el-radio-group
                    v-model="afterSaleForm.reject_mode"
                    @change="changeMode"
                  >
                    <el-radio
                      :label="
                        typeof afterSaleForm.reject_mode == 'string' ? '1' : 1
                      "
                      >7天无理由退换货</el-radio
                    ><el-radio
                      :label="
                        typeof afterSaleForm.reject_mode == 'string' ? '0' : 0
                      "
                      >不支持退换货</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="退换货说明" prop="reject_info">
                  <el-input
                    placeholder=" 请输入，将用于客户端展示（建议10字以内）"
                    v-model="afterSaleForm.reject_info"
                  >
                  </el-input>
                </el-form-item>
              </el-card>
            </div>
            <div v-else>
              <el-card>
                <el-form-item label="是否设置自动确认收货">
                  <span v-if="afterSaleForm.is_auto_confirm == 1">是</span>
                  <span v-if="afterSaleForm.is_auto_confirm == 0">否</span>
                </el-form-item>
                <el-form-item
                  label="自动确认收货时间"
                  v-show="afterSaleForm.is_auto_confirm == 1"
                >
                  <span>{{ afterSaleForm.timeout_auto_confirm }}天</span>
                </el-form-item>
                <el-form-item label="退换货">
                  <span v-if="afterSaleForm.reject_mode == 1"
                    >7天无理由退换货</span
                  >
                  <span v-if="afterSaleForm.reject_mode == 0"
                    >不支持退换货</span
                  >
                </el-form-item>
                <el-form-item label="退换货说明">
                  <span>{{ afterSaleForm.reject_info }}</span>
                </el-form-item>
              </el-card>
            </div>
          </el-form>
          <el-row style="margin-top: 20px">
            <el-button
              class="theme-background-color"
              @click="saveDistributionAfterSaleData"
              v-if="
                (distributionForm.id == '' ||
                  distributionForm.editFlag == true) &&
                (afterSaleForm.id == '' || afterSaleForm.editFlag == true)
              "
            >
              保存
            </el-button>
            <el-button
              class="theme-background-color"
              @click="
                distributionForm.editFlag = true
                afterSaleForm.editFlag = true
              "
              v-else
            >
              编辑
            </el-button>
          </el-row>
          <ChooseMultiHospitalDialog
            :chooseMultiHospitalDialogVisible.sync="
              chooseMultiHospitalDialogVisible
            "
            :hostpitalOptionalData="hostpitalOptionalData"
            @showHospitalData="getHospitalData"
          ></ChooseMultiHospitalDialog>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import ChooseMultiHospitalDialog from './ChooseMultiHospitalDialog.vue'
import ChooseMultiCommodityDialog from './ChooseMultiCommodityDialog.vue'
export default {
  components: { ChooseMultiHospitalDialog, ChooseMultiCommodityDialog },
  data() {
    return {
      activeName: 'first',

      // 问诊派单规则tab数据
      assignForm: {
        id: '',
        rule: 1,
        timeout: '',
        dispatch_mode: 1,
        editFlag: true
      },
      assignFormRules: {
        rule: [{ required: true, message: '请选择', trigger: 'change' }],
        timeout: [
          { required: true, message: '请输入', trigger: 'blur' },
          { type: 'number', message: '必须为数字值' }
        ],
        dispatch_mode: [
          { required: true, message: '请选择', trigger: 'change' }
        ]
      },
      // dispatchRuleForm: { dispatchRuleTableData: [] },
      // dispatchRuleFormRules: {
      //   sort: [{ required: true, message: '请选择', trigger: 'change' }]
      // },

      // 药品提成配置tab数据
      drugCommissionForm: { id: '', rule: '1', rate: '', editFlag: true },
      drugCommissionFormRules: {
        rule: [{ required: true, message: '请选择', trigger: 'change' }],
        rate: [
          { required: true, message: '请输入', trigger: 'blur' },
          { type: 'number', message: '必须为数字值' }
        ]
      },
      dispatchRuleAllData: [],

      // 推广提成配置tab数据
      popularizeForm: {
        id: '',
        entity_type: '',
        rule: '',
        editFlag: true
      },
      popularizeFormRules: {
        entity_type: [{ required: true, message: '请选择', trigger: 'change' }],
        rule: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      popularizeRuleForm: {
        ruleTableData: []
      },
      popularizeRuleFormRules: {
        fee: [{ required: true, message: '请输入', trigger: 'blur' }]
      },
      chooseMultiCommodityDialogVisible: false,
      commodityAllData: [], //所有的商品数据
      commodityOptionalData: [], //去掉配送规则表后可供选择的商品数据

      // 配送售后配置tab数据
      // 配送规则
      distributionForm: { id: '', rule: '', time_long: '', editFlag: true },
      distributionFormRules: {
        rule: [{ required: true, message: '请选择', trigger: 'change' }],
        time_long: [
          { required: true, message: '请输入', trigger: 'blur' },
          { type: 'number', message: '必须为数字值' }
        ]
      },
      distributionRuleForm: {
        distributionRulesTable: []
      },
      distributionRuleFormRules: {
        range: [{ required: true, message: '请输入', trigger: 'blur' }],
        fee: [{ required: true, message: '请输入', trigger: 'blur' }]
      },
      chooseMultiHospitalDialogVisible: false,
      hospitalAllData: [], //所有的医院数据
      hostpitalOptionalData: [], //去掉配送规则表后可供选择的医院数据
      // 售后规则
      afterSaleForm: {
        is_auto_confirm: '1',
        timeout_auto_confirm: '',
        reject_mode: '',
        reject_info: '退换货',
        editFlag: true
      },
      afterSaleFormRules: {
        is_auto_confirm: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        reject_mode: [{ required: true, message: '请选择', trigger: 'change' }],
        reject_info: [{ required: true, message: '请输入', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getSelectData()
    this.getAssignData()
    this.getDrugCommissionData()
    this.getSpreadData()
    this.getDistributionData()
  },
  methods: {
    async getAssignData() {
      const { data: res } = await this.$http.get('/admin/drconfig/question')
      // 返回结果
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.handleAssignData(res.data)
    },
    handleAssignData(data) {
      for (const key in this.assignForm) {
        // console.log(key, data[key])
        this.assignForm[key] = data[key]
      }
      if (this.assignForm.id == '') {
        this.assignForm.editFlag = true
      } else {
        this.assignForm.editFlag = false
      }
      // console.log(this.assignForm)
      this.dispatchRuleAllData = data.detail
      // this.handlePriority()
    },
    // 判断是否是编辑页(非编辑页不展示没有优先级的数据)
    // handlePriority() {
    //   let tempData = JSON.parse(JSON.stringify(this.dispatchRuleAllData))
    //   if (this.assignForm.id == '' || this.assignForm.editFlag == true) {
    //     // 全部的数据
    //     this.dispatchRuleForm.dispatchRuleTableData = tempData

    //     this.$nextTick(() => {
    //       this.dispatchRuleForm.dispatchRuleTableData.forEach((row) => {
    //         if (row.sort > 0) {
    //           this.$refs.multipleTable.toggleRowSelection(row, true)
    //         } else {
    //           row.sort = ''
    //         }
    //       })
    //     })
    //   } else {
    //     for (let i = 0; i < tempData.length; i++) {
    //       if (tempData[i].sort == '') {
    //         delete tempData[i]
    //       }
    //     }
    //     this.dispatchRuleForm.dispatchRuleTableData = tempData
    //     console.log(tempData)
    //   }
    // },

    async getDrugCommissionData() {
      const { data: res } = await this.$http.get('/admin/drconfig/drug')
      // 返回结果
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.handleDrugCommissionData(res.data)
    },
    handleDrugCommissionData(data) {
      for (const key in this.drugCommissionForm) {
        this.drugCommissionForm[key] = data[key]
      }
    },
    async getSpreadData() {
      const { data: res } = await this.$http.get('/admin/drconfig/spread')
      // 返回结果
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.handleSpreadData(res.data)
    },
    // 处理数据
    handleSpreadData(data) {
      for (const key in this.popularizeForm) {
        this.popularizeForm[key] = data[key]
      }
      this.popularizeRuleForm.ruleTableData = data.detail
    },
    async getDistributionData() {
      const { data: res } = await this.$http.get('/admin/drconfig/express')
      // 返回结果
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.handleDistributionData(res.data)
    },
    // 处理数据
    handleDistributionData(data) {
      for (const key in this.distributionForm) {
        this.distributionForm[key] = data[key]
      }
      this.distributionRuleForm.distributionRulesTable = data.detail
      data.reject_info = data.reject_info ? data.reject_info : '退换货'
      for (const key in this.afterSaleForm) {
        this.afterSaleForm[key] = data[key]
      }
    },
    async getSelectData() {
      const { data: res } = await this.$http.post('/admin/data/find', {
        code: 'get_hospital_tree,get_goods_tree'
      })
      // 返回结果
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.hospitalAllData = res.data.get_hospital_tree
      this.commodityAllData = res.data.get_goods_tree
    },
    tableRowClassName({ row, rowIndex }) {
      //   把每一行的索引放进row
      row.index = rowIndex
    },
    // 对部分表单字段进行校验
    validateField(form, index) {
      let result = true
      for (let item of this.$refs[form].fields) {
        if (item.prop.split('.')[1] == index) {
          this.$refs[form].validateField(item.prop, (error) => {
            if (error != '') {
              result = false
            }
          })
        }
        if (!result) break
      }
      return result
    },
    //对部分表单字段进行重置
    resetField(form, index) {
      this.$refs[form].fields.forEach((item) => {
        if (item.prop.split('.')[1] == index) {
          item.resetField()
        }
      })
    },
    handleSelect(selection, row) {
      console.log(selection, row)
      let selected = selection.length && selection.indexOf(row) !== -1
      console.log(selected) // true就是选中，0或者false是取消选中
      if (selected) {
        row.status = 1
        if (!this.validateField('dispatchRuleFormRef', row.index)) {
          return
        }
      } else {
        this.resetField('dispatchRuleFormRef', row.index)
        row.status = 0
        row.sort = ''
      }
    },
    clearSelect(index) {
      this.resetField('dispatchRuleFormRef', index)
    },
    changePriority(val, row) {
      console.log(val)
    },
    checkPriority(data) {
      let numArray = []
      for (let i = 0; i < data.length; i++) {
        numArray.push(data[i].sort)
      }
      numArray.sort()
      console.log(numArray)

      // 校验是否连续
      var i = numArray[0]
      var isContinuation = true
      for (var e in numArray) {
        if (numArray[e] != i) {
          isContinuation = false
          break
        }
        i++
      }
      console.log(isContinuation)
      return isContinuation
    },
    saveaAssignData() {
      this.$refs.assignFormRef.validate(async (valid) => {
        if (!valid) return

        // const detail = this.dispatchRuleForm.dispatchRuleTableData
        // // 筛选选中的数据
        // let multipleSelection = []
        // for (let i = 0; i < detail.length; i++) {
        //   const item = detail[i]
        //   if (item.status == 1) {
        //     multipleSelection.push(item)
        //   } else {
        //     item.sort = ''
        //   }
        // }
        // if (multipleSelection.length == 0) {
        //   return this.$message.error('请选择派单规则')
        // }
        // // 按index排序再校验优先级必选
        // multipleSelection.sort((a, b) => (a['index'] > b['index'] ? 1 : -1))
        // console.log(multipleSelection)

        // for (let i = 0; i < multipleSelection.length; i++) {
        //   if (
        //     !this.validateField(
        //       'dispatchRuleFormRef',
        //       multipleSelection[i].index
        //     )
        //   ) {
        //     return
        //   }
        // }
        // // 校验优先级
        // if (!this.checkPriority(multipleSelection)) {
        //   return this.$message.error('优先级设置有误')
        // }
        // console.log(this.assignForm, detail)

        // const postData = Object.assign(this.assignForm, {
        //   detail: JSON.stringify(detail)
        // })
        const { data: res } = await this.$http.post(
          '/admin/drconfig/question',
          this.assignForm
        )
        // 返回结果
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success('保存成功')
        this.handleAssignData(res.data)
        this.assignForm.editFlag = false
      })
    },
    saveSpreadData() {
      this.$refs.popularizeFormRef.validate(async (valid) => {
        if (!valid) return

        if (this.popularizeRuleForm.ruleTableData.length == 0) {
          return this.$message.error('请配置提成规则')
        }

        if (!this.validateFieldAll('popularizeRuleFormRef')) {
          return
        }
        // console.log(
        //   this.popularizeForm,
        //   this.popularizeRuleForm.ruleTableData
        // )

        const postData = Object.assign(this.popularizeForm, {
          detail: JSON.stringify(this.popularizeRuleForm.ruleTableData)
        })
        const { data: res } = await this.$http.post(
          '/admin/drconfig/spread',
          postData
        )
        // 返回结果
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success('保存成功')
        this.handleSpreadData(res.data)
        this.popularizeForm.editFlag = false
      })
    },
    saveCommissionData() {
      this.$refs.drugCommissionFormRef.validate(async (valid) => {
        if (!valid) return

        console.log(this.drugCommissionForm)
        const { data: res } = await this.$http.post(
          '/admin/drconfig/drug',
          this.drugCommissionForm
        )
        // 返回结果
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success('保存成功')
        this.handleDrugCommissionData(res.data)
        this.drugCommissionForm.editFlag = false
      })
    },
    addCommodity() {
      // 已选中的商品id数组
      const checkedIdArr = this.popularizeRuleForm.ruleTableData.map((x) => {
        return x.goods_id
      })
      console.log(checkedIdArr)

      let tempArray = []
      if (checkedIdArr.length > 0) {
        // 筛掉已选中的数据
        for (let i = 0; i < this.commodityAllData.length; i++) {
          let childrenArr = []
          for (
            let j = 0;
            j < this.commodityAllData[i]['children'].length;
            j++
          ) {
            if (
              checkedIdArr.indexOf(
                this.commodityAllData[i]['children'][j].id
              ) == -1
            ) {
              childrenArr.push(this.commodityAllData[i]['children'][j])
            }
          }
          if (childrenArr.length > 0) {
            let tempItem = {
              id: this.commodityAllData[i].class_id,
              name: this.commodityAllData[i].class_name,
              children: childrenArr
            }
            tempArray.push(tempItem)
          }
        }
      } else {
        for (let i = 0; i < this.commodityAllData.length; i++) {
          let tempItem = {
            id: this.commodityAllData[i].class_id,
            name: this.commodityAllData[i].class_name,
            children: this.commodityAllData[i].children
          }
          tempArray.push(tempItem)
        }
      }
      console.log(tempArray)
      this.commodityOptionalData = tempArray
      console.log(this.commodityOptionalData)
      this.chooseMultiCommodityDialogVisible = true
      console.log(this.chooseMultiCommodityDialogVisible)
    },
    handleCommodityData(data) {
      // 已选中的商品id数组
      let checkedIdArr = data.map((x) => {
        return x.id
      })
      let tempArray = []
      for (let i = 0; i < this.commodityAllData.length; i++) {
        for (let j = 0; j < this.commodityAllData[i]['children'].length; j++) {
          if (
            checkedIdArr.indexOf(this.commodityAllData[i]['children'][j].id) !=
            -1
          ) {
            tempArray.push({
              goods_id: this.commodityAllData[i]['children'][j].id,
              goods_name: this.commodityAllData[i]['children'][j].name,
              goods_class: {
                id: this.commodityAllData[i].class_id,
                name: this.commodityAllData[i].class_name
              },
              fee: ''
            })
          }
        }
      }
      return tempArray
    },
    getCommodityData(data) {
      console.log(data)
      // 处理数据
      const newData = this.handleCommodityData(data)
      console.log(newData)
      newData.forEach((element) => {
        this.popularizeRuleForm.ruleTableData.push(element)
      })
    },
    deleteCommodity(index) {
      this.popularizeRuleForm.ruleTableData.splice(index, 1)
    },
    addHospital() {
      // 已选中的医院id数组
      let checkedHospitalIdArr =
        this.distributionRuleForm.distributionRulesTable.map((x) => {
          return x.hospital_id
        })
      console.log(checkedHospitalIdArr)

      let tempArray = []
      if (checkedHospitalIdArr.length > 0) {
        // 筛掉已选中的数据
        for (let i = 0; i < this.hospitalAllData.length; i++) {
          let childrenArr = []
          for (let j = 0; j < this.hospitalAllData[i]['children'].length; j++) {
            if (
              checkedHospitalIdArr.indexOf(
                this.hospitalAllData[i]['children'][j].id
              ) == -1
            ) {
              childrenArr.push(this.hospitalAllData[i]['children'][j])
            }
          }
          if (childrenArr.length > 0) {
            let tempItem = {
              id: this.hospitalAllData[i].id,
              name: this.hospitalAllData[i].name,
              children: childrenArr
            }
            tempArray.push(tempItem)
          }
        }
      } else {
        tempArray = JSON.parse(JSON.stringify(this.hospitalAllData))
      }
      console.log(tempArray)
      this.hostpitalOptionalData = tempArray
      console.log(this.hostpitalOptionalData)
      this.chooseMultiHospitalDialogVisible = true
      console.log(this.chooseMultiHospitalDialogVisible)
    },
    // 补全服务商信息
    handleHospitalData(data) {
      // 已选中的医院id数组
      let checkedHospitalIdArr = data.map((x) => {
        return x.id
      })
      let tempArray = []
      for (let i = 0; i < this.hospitalAllData.length; i++) {
        for (let j = 0; j < this.hospitalAllData[i]['children'].length; j++) {
          if (
            checkedHospitalIdArr.indexOf(
              this.hospitalAllData[i]['children'][j].id
            ) != -1
          ) {
            tempArray.push({
              hospital_id: this.hospitalAllData[i]['children'][j].id,
              hospital_name: this.hospitalAllData[i]['children'][j].name,
              provider_id: this.hospitalAllData[i].id,
              provider_name: this.hospitalAllData[i].name,
              range: '',
              fee: ''
            })
          }
        }
      }
      return tempArray
    },
    getHospitalData(data) {
      console.log(data)
      // 处理数据
      const newData = this.handleHospitalData(data)
      console.log(newData)
      newData.forEach((element) => {
        this.distributionRuleForm.distributionRulesTable.push(element)
      })
    },
    deleteHospital(index) {
      this.distributionRuleForm.distributionRulesTable.splice(index, 1)
    },
    // 对部分表单字段进行校验
    validateFieldAll(form, index = '') {
      let result = true
      for (let item of this.$refs[form].fields) {
        this.$refs[form].validateField(item.prop, (error) => {
          //   console.log(item.prop)
          if (error != '') {
            result = false
          }
        })
        if (!result) break
      }
      return result
    },
    changeMode(val) {
      console.log(val)
      if (val == 1) {
        this.afterSaleForm.reject_info = '7天无理由退换货'
      } else {
        this.afterSaleForm.reject_info = '不支持退换货'
      }
    },
    saveDistributionAfterSaleData() {
      this.$refs.distributionFormRef.validate((valid) => {
        if (!valid) return

        if (this.distributionRuleForm.distributionRulesTable.length == 0) {
          return this.$message.error('请配置配送规则')
        }

        if (!this.validateFieldAll('distributionRuleFormRef')) {
          return
        }
        // console.log(
        //   this.distributionForm,
        //   this.distributionRuleForm.distributionRulesTable
        // )

        this.$refs.afterSaleFormRef.validate(async (valid2) => {
          if (!valid2) return
          console.log(this.afterSaleForm)

          const postData = Object.assign(
            this.distributionForm,
            this.afterSaleForm,
            {
              detail: JSON.stringify(
                this.distributionRuleForm.distributionRulesTable
              )
            }
          )
          const { data: res } = await this.$http.post(
            '/admin/drconfig/express',
            postData
          )
          // 返回结果
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.$message.success('保存成功')
          this.handleDistributionData(res.data)
          this.distributionForm.editFlag = false
          this.afterSaleForm.editFlag = false
        })
      })
    },
    changeTab(activeName, oldActiveName) {
      if (
        (oldActiveName == 'first' && this.assignForm.editFlag == true) ||
        (oldActiveName == 'second' &&
          this.drugCommissionForm.editFlag == true) ||
        (oldActiveName == 'fourth' &&
          this.distributionForm.editFlag == true &&
          this.afterSaleForm.editFlag == true)
      ) {
        var p = new Promise((resolve, reject) => {
          this.$confirm('离开将不保存本页修改', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              // 你可以在这儿做些操作
              switch (oldActiveName) {
                case 'first':
                  this.getAssignData()
                  break
                case 'second':
                  this.getDrugCommissionData()
                  break
                case 'fourth':
                  this.getDistributionData()
                  break
              }
              resolve()
            })
            .catch((err) => {
              // 你可以在这儿做些操作
              this.$message.info('已取消操作')
              reject(err)
            })
        })
        return p
      }
    }
  }
  // watch: {
  //   'assignForm.editFlag'() {
  //     console.log(this.assignForm.editFlag)

  //     this.handlePriority()
  //   }
  // }
}
</script>

<style lang="less" scoped>
/deep/.tabs {
  .el-tabs__item {
    font-size: 20px;
  }
  .el-tabs__item.is-active {
    color: #009688;
  }
  .el-tabs__active-bar {
    background-color: #009688;
  }
  .el-tabs__item:hover {
    color: #009688;
  }
}
.el-form {
  margin: 10px 0;
  .el-select {
    width: 100%;
  }
}
.greenTitle {
  font-size: 18px;
  color: #009688;
}
</style>
